/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.Memory;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.Server;
import it.polimi.games.epkb.entityClasses.Component;
import java.util.ArrayList;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class MemoryJpaController implements Serializable {

    public MemoryJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public MemoryJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Memory memory) throws IllegalOrphanException, PreexistingEntityException, Exception {
        List<String> illegalOrphanMessages = null;
        Component componentOrphanCheck = memory.getComponent();
        if (componentOrphanCheck != null) {
            Memory oldMemoryOfComponent = componentOrphanCheck.getMemory();
            if (oldMemoryOfComponent != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("The Component " + componentOrphanCheck + " already has an item of type Memory whose component column cannot be null. Please make another selection for the component field.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Server idServer = memory.getIdServer();
            if (idServer != null) {
                idServer = em.getReference(idServer.getClass(), idServer.getId());
                memory.setIdServer(idServer);
            }
            Component component = memory.getComponent();
            if (component != null) {
                component = em.getReference(component.getClass(), component.getId());
                memory.setComponent(component);
            }
            em.persist(memory);
            if (idServer != null) {
                idServer.getMemoryCollection().add(memory);
                idServer = em.merge(idServer);
            }
            if (component != null) {
                component.setMemory(memory);
                component = em.merge(component);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findMemory(memory.getId()) != null) {
                throw new PreexistingEntityException("Memory " + memory + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Memory memory) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Memory persistentMemory = em.find(Memory.class, memory.getId());
            Server idServerOld = persistentMemory.getIdServer();
            Server idServerNew = memory.getIdServer();
            Component componentOld = persistentMemory.getComponent();
            Component componentNew = memory.getComponent();
            List<String> illegalOrphanMessages = null;
            if (componentNew != null && !componentNew.equals(componentOld)) {
                Memory oldMemoryOfComponent = componentNew.getMemory();
                if (oldMemoryOfComponent != null) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("The Component " + componentNew + " already has an item of type Memory whose component column cannot be null. Please make another selection for the component field.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idServerNew != null) {
                idServerNew = em.getReference(idServerNew.getClass(), idServerNew.getId());
                memory.setIdServer(idServerNew);
            }
            if (componentNew != null) {
                componentNew = em.getReference(componentNew.getClass(), componentNew.getId());
                memory.setComponent(componentNew);
            }
            memory = em.merge(memory);
            if (idServerOld != null && !idServerOld.equals(idServerNew)) {
                idServerOld.getMemoryCollection().remove(memory);
                idServerOld = em.merge(idServerOld);
            }
            if (idServerNew != null && !idServerNew.equals(idServerOld)) {
                idServerNew.getMemoryCollection().add(memory);
                idServerNew = em.merge(idServerNew);
            }
            if (componentOld != null && !componentOld.equals(componentNew)) {
                componentOld.setMemory(null);
                componentOld = em.merge(componentOld);
            }
            if (componentNew != null && !componentNew.equals(componentOld)) {
                componentNew.setMemory(memory);
                componentNew = em.merge(componentNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = memory.getId();
                if (findMemory(id) == null) {
                    throw new NonexistentEntityException("The memory with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Memory memory;
            try {
                memory = em.getReference(Memory.class, id);
                memory.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The memory with id " + id + " no longer exists.", enfe);
            }
            Server idServer = memory.getIdServer();
            if (idServer != null) {
                idServer.getMemoryCollection().remove(memory);
                idServer = em.merge(idServer);
            }
            Component component = memory.getComponent();
            if (component != null) {
                component.setMemory(null);
                component = em.merge(component);
            }
            em.remove(memory);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Memory> findMemoryEntities() {
        return findMemoryEntities(true, -1, -1);
    }

    public List<Memory> findMemoryEntities(int maxResults, int firstResult) {
        return findMemoryEntities(false, maxResults, firstResult);
    }

    private List<Memory> findMemoryEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Memory.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Memory findMemory(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Memory.class, id);
        } finally {
            em.close();
        }
    }

    public int getMemoryCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Memory> rt = cq.from(Memory.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
